<?php

namespace app\api\controller;

use app\admin\model\Bill;
use app\admin\model\Studentinfo;
use app\beans\Body;
use app\beans\ChargeBillResponseHead;
use app\beans\ChargeBillResponseInfo;
use app\beans\Message;
use app\beans\QueryBillResponseHead;
use app\beans\QueryBillResponseInfo;
use app\common\controller\Api;
use app\sign\SignatureAndVerification;
use app\utils\HttpClientUtils;
use app\utils\TimeUtils;
use think\Db;
use think\Log;
use think\Response;

/**
 * 示例接口
 */
class Open extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['querypay', 'downpay'];

    /**
     * 账号参与条件
     *
     */
    public function querypay()
    {
        $util = new HttpClientUtils();
        $requestMap = $util->requestBodyOfBase64();

        //使用base64解析完成后的requestBody
        $requestBodyOfDecoded = $requestMap['requestBodyOfDecoded'];
        //解析前的requestBody
        $requestBody = $requestMap['requestBody'];
        //获取缴费中心传送过来的签名
        $signatureString = $requestMap['signatureString'];
        $result = (string)SignatureAndVerification::read_cer_and_verify_sign($requestBody,$signatureString);
        Log::info("获取到的报文验签的结果为：".$result);
        if ('1' !== $result) {
            $responseStr = '验签失败！';
        }else {

            $respHead = new QueryBillResponseHead();
            $respInfo = new QueryBillResponseInfo();
            $respBill = new QueryBillResponseInfo\Bill();

            //      封装info信息
            $respInfo->setEpayCode(isset($requestBodyOfDecoded->message->info->epayCode) ? $requestBodyOfDecoded->message->info->epayCode : null);
            $respInfo->setMerchantId(isset($requestBodyOfDecoded->message->info->merchantId) ? $requestBodyOfDecoded->message->info->merchantId : null);
            $respInfo->setTraceNo(isset($requestBodyOfDecoded->message->info->traceNo) ? $requestBodyOfDecoded->message->info->traceNo : null);
            $respInfo->setInput1(isset($requestBodyOfDecoded->message->info->input1) ? $requestBodyOfDecoded->message->info->input1 : null);
            $respInfo->setInput2(isset($requestBodyOfDecoded->message->info->input2) ? $requestBodyOfDecoded->message->info->input2 : null);
            $respInfo->setInput3(isset($requestBodyOfDecoded->message->info->input3) ? $requestBodyOfDecoded->message->info->input3 : null);
            $respInfo->setInput4(isset($requestBodyOfDecoded->message->info->input4) ? $requestBodyOfDecoded->message->info->input4 : null);
            $respInfo->setInput5(isset($requestBodyOfDecoded->message->info->input5) ? $requestBodyOfDecoded->message->info->input5 : null);

//            $respInfo->setCustName("张三丰");
//            $respInfo->setCustAddress("北京海淀区温泉凯盛家园1区1号楼2单元999室");
//            $respInfo->setCacheMem("0,0.00,S,张三丰,4340152");
//            $respInfo->setRemark("备注信息为空");
//            $respInfo->setAmtRule('0');
//            $respInfo->setCallBackUrl("d3d3LmFiY2hpbmEuY29tL2NuLw==");
//            $respInfo->setCallBackText("中国农业银行官网");

            //      封装info内部类bill内部的descDtail
//            $descDtail1 = new QueryBillResponseInfo\DescDetail("缴费月份:", "2018年6月份");
//            $descDtail2 = new QueryBillResponseInfo\DescDetail("供电局编号:", "4340152");
//            $descDtail3 = new QueryBillResponseInfo\DescDetail("欠费金额:", "0.01元");
//            $descDtail4 = new QueryBillResponseInfo\DescDetail("缴费月份:", "2018年6月份");
//            $descDtail5 = new QueryBillResponseInfo\DescDetail("服务时间:", "每天0:30-23:30期间均可缴费");
//            $descDtail6 = new QueryBillResponseInfo\DescDetail("温馨提示:", "北京电力电费代缴，咨询电话：95598 该用户为：预付费用户");
//            $respDescDetail = array($descDtail1, $descDtail2, $descDtail3, $descDtail4, $descDtail5, $descDtail6);
            //      封装info内部类bill内部的unitDetail
            $unitDetail = new QueryBillResponseInfo\UnitDetail("unitName", "6.66", "1");
            //      封装info内部类bill，并将其转化为array形式封装给info
            $respBill->setUnitDetail($unitDetail);

            $respBill->setOweAmt(isset($requestBodyOfDecoded->message->info->input4) ? $requestBodyOfDecoded->message->info->input4 : 0);
            $payamt=isset($requestBodyOfDecoded->message->info->input4) ? $requestBodyOfDecoded->message->info->input4 : 0;
            $respBill->setBillNo(isset($requestBodyOfDecoded->message->info->traceNo) ? $requestBodyOfDecoded->message->info->traceNo : "");
            $respBill->setBillName("江西工商高级技工学费");

            $respBill->setFeeAmt("0.00");
//            $respBill->setExpireDate("20230731");
//            $respBill->setDescDetails($respDescDetail);
            $respBills = array($respBill);

            $respInfo->setTotalBillCount('1');
            $respInfo->setBills($respBills);

            //       封装响应的消息头信息
            $respHead->setTransSeqNum($requestBodyOfDecoded->message->head->transSeqNum);
            $respHead->setTransCode($requestBodyOfDecoded->message->head->transCode);
            $respHead->setChannel($requestBodyOfDecoded->message->head->channel);

            $respHead->setTransFlag("02");
            $respHead->setTimeStamp(TimeUtils::getTimeStamp('YmdHisu'));
            //$respHead->setReturnCode("0000");

            //$nbill = new Bill();
            //身份证号
            $idno=$respInfo->input2;

            //类别
            $kind=$respInfo->input5;
            $where['input5'] = ['=',$kind];

 //           $ttt= Db::table('fa_bill')->where('input2',$idno)->where($where)->find();
            //是否加新学期来判断
//            if ($ttt==null){
//                $respHead->setReturnCode("0000");
//            }else{
//                //上学期已交过
//                //未查询到账单
//                //$respHead->setReturnCode("JH14");
//            }
            $wheresta = [];
            $wheresta['status'] = ['in', ['0','1','2']];

            $list= Db::table('fa_studentinfo')->where('idno',$idno)->where($wheresta)->order('id desc')->find();
            if($list==null){
                $list= Db::table('fa_studentinfo')->where('idno',$idno)->order('id desc')->find();
                $respHead->setReturnCode("JH05");
                $respHead->setReturnMessage("请输入正确的学生身份证号！");
            }

            $pay1 =$list['pay1'];
            $pay2 =$list['pay2'];
            $pay3 =$list['pay3'];
            $pay4=$list['pay4'];
            $pay6 =$list['pay6'];
            $pay7 =$list['pay7'];
            $pay8 =$list['pay8'];
            $pay9 =$list['pay9'];
            $pay5 =$list['pay5'];

            //工商学校只有学费，住宿费，教材费，学费pay1 ,住宿费pay2 ,教材费pay9 ,
            //教材费  pay3=pay9
            //学费住宿费 pay4=pay1+pay2+pay9 传过来永远是pay4
            //只可能由学费或者学费类 pay9=0时是学费类，
            //pay3 是技能鉴定费
            //pay8是培训费


            $payother=number_format($pay1+$pay2, 2);
            $payone=number_format($pay1+$pay2+$pay9+$pay3+$pay8, 2);
            $payamt=number_format($payamt, 2);
            if($kind=='学费'||$kind=='A'){
                if($payone==$payamt){
                    $respHead->setReturnCode("0000");
                    $respHead->setReturnMessage("账单查询成功，返回成功标志");
                }else{
                    $respHead->setReturnCode("JF05");
                    $respHead->setReturnMessage("请重新扫码识别账单！");
                }
            }else if($kind=='学费类'||$kind=='C'){
                if($payone==$payamt){
                    $respHead->setReturnCode("0000");
                    $respHead->setReturnMessage("账单查询成功，返回成功标志");
                }else{
                    $respHead->setReturnCode("JF05");
                    $respHead->setReturnMessage("请重新扫码识别账单！");
                }
            }else{
                $respHead->setReturnCode("JH11");
                $respHead->setReturnMessage("暂不支持该渠道！");
            }


//            if($kind=='学费'||$kind=='A'){
//                if($payone==$payamt){
//                    $respHead->setReturnCode("0000");
//                    $respHead->setReturnMessage("账单查询成功，返回成功标志");
//                }else{
//                    $respHead->setReturnCode("JF05");
//                    $respHead->setReturnMessage("缴费金额不足，如有疑问请联系老师！");
//                }
//            }else if($kind=='学杂费'||$kind=='B'){
//                if($payother==$payamt){
//                    $respHead->setReturnCode("0000");
//                    $respHead->setReturnMessage("账单查询成功，返回成功标志");
//                }else{
//                    $respHead->setReturnCode("JF05");
//                    $respHead->setReturnMessage("缴费金额不足，如有疑问请联系老师！");
//                }
//            }else if($kind=='学费类'||$kind=='C'){
//                if($payone==$payamt){
//                    $respHead->setReturnCode("0000");
//                    $respHead->setReturnMessage("账单查询成功，返回成功标志");
//                }else{
//                    $respHead->setReturnCode("JF05");
//                    $respHead->setReturnMessage("缴费金额不足，如有疑问请联系老师！");
//                }
//            }else if($kind=='学杂费类'||$kind=='D'){
//                if($payother==$payamt){
//                    $respHead->setReturnCode("0000");
//                    $respHead->setReturnMessage("账单查询成功，返回成功标志");
//                }else{
//                    $respHead->setReturnCode("JF05");
//                    $respHead->setReturnMessage("缴费金额不足，如有疑问请联系老师！");
//                }
//            }else{
//                $respHead->setReturnCode("JH11");
//                $respHead->setReturnMessage("暂不支持该渠道！");
//            }

            //Plocn::plocntest($respInfo->input2);
//            JH03 该业务已暂停
//            JH04 非业务时间
//            JH10该业务不支持异地办理，请选择正确的城市
//            JH11暂不支持该渠道
//            JH14缴费次数超出限制



            $respMessage = new Message($respInfo, $respHead, $requestBodyOfDecoded->message->info, $requestBodyOfDecoded->message->head);
            $responseBody = new Body($requestBodyOfDecoded->format, $respMessage);
            $responseJson = json_encode($responseBody, JSON_UNESCAPED_UNICODE);
            Log::info("向后台发送的报文加密前为：" . $responseJson);
            if($respInfo->epayCode=="JF-EPAY2021082332174") {
                //还是象湖的，用不同的证书
                // 加签名
                $signatrue = SignatureAndVerification::sign_with_sha1_with_rsa($responseJson);
            }else{
                //判断是祥能
                // 加签名
                $signatrue = SignatureAndVerification::sign_with_sha1_with_rsabowang($responseJson);
            }

            $responseStr = $signatrue . "||" . (base64_encode($responseJson));

        }
        Log::info("向后台发送的报文加密后为：".$responseStr);
//      将加签名之后的报文发送给浏览器
        $httpresp = new Response();
        $httpresp->contentType('text/plain','utf-8');
        $httpresp->data($responseStr);

        $httpresp->send();
    }

    /**
     * 支付成功回调销账接口
     *
     */
    public function downpay()
    {
        $util = new HttpClientUtils();
        $requestMap = $util->requestBodyOfBase64();

        //使用base64解析完成后的requestBody
        $requestBodyOfDecoded = $requestMap['requestBodyOfDecoded'];
        //解析前的requestBody
        $requestBody = $requestMap['requestBody'];
        //获取缴费中心传送过来的签名
        $signatureString = $requestMap['signatureString'];
        $result = (string)SignatureAndVerification::read_cer_and_verify_sign($requestBody,$signatureString);
        if ('1' !== $result){
            $responseStr = '验签失败！';
        }else {

            $respHead = new ChargeBillResponseHead();
            $respInfo = new ChargeBillResponseInfo();

            /** 销账报文重发次数，通过此字段识别销账报文是否为重发的，0表示首次、1表示重发一次，2表示重发2次，最多重发3次*/
            //$resendTimes = isset($requestBodyOfDecoded->message->info->resendTimes) ? $requestBodyOfDecoded->message->info->resendTimes : "";
            /** 第三方支付平台商户订单号 */
            $numOpenMerchantOrder= isset($requestBodyOfDecoded->message->info->numOpenMerchantOrder) ? $requestBodyOfDecoded->message->info->numOpenMerchantOrder : "";

            $respHead->setTransFlag("02");
            $respHead->setTimeStamp(TimeUtils::getTimeStamp('YmdHisu'));
            $respHead->setChannel(isset($requestBodyOfDecoded->message->head->channel) ? $requestBodyOfDecoded->message->head->channel : "");
            //        $respHead->setChannel("MBNK");
            $respHead->setTransCode(isset($requestBodyOfDecoded->message->head->transCode) ? $requestBodyOfDecoded->message->head->transCode : "");
            //        $respHead->setTransCode("chargeBill");
            $respHead->setTransSeqNum(isset($requestBodyOfDecoded->message->head->transSeqNum) ? $requestBodyOfDecoded->message->head->transSeqNum : "");
            //        $respHead->setReturnCode("1111");


            $epayCode = isset($requestBodyOfDecoded->message->info->epayCode) ? $requestBodyOfDecoded->message->info->epayCode : "";
            $traceNo = isset($requestBodyOfDecoded->message->info->traceNo) ? $requestBodyOfDecoded->message->info->traceNo : "";
            $respInfo->setTraceNo($traceNo);
            $respInfo->setEpayCode($epayCode);
            $respInfo->setNumOpenMerchantOrder($numOpenMerchantOrder);
            /**
             * 返回码为0000时不读取本字段；
             * 返回码非0000时，必须返回本标志位信息。返回true标志自动实时退款，返回false标志不做退款
             *
             * 根据账单请求次数确定返回参数，分为四种情况。
             */

            $respHead->setReturnCode("0000");
            $respHead->setReturnMessage("账单缴费成功！");
            $respInfo->setRefundFlag("true");

            $respMessage = new Message($respInfo, $respHead, $requestBodyOfDecoded->message->info, $requestBodyOfDecoded->message->head);
            $responseBody = new Body($requestBodyOfDecoded->format, $respMessage);
            $responseJson = json_encode($responseBody, JSON_UNESCAPED_UNICODE);
            if($respInfo->epayCode=="JF-EPAY2021082332174") {
                //还是外国语的，用不同的证书
                // 加签名
                $signatrue = SignatureAndVerification::sign_with_sha1_with_rsa($responseJson);
            }else{
                //判断是博望
                // 加签名
                $signatrue = SignatureAndVerification::sign_with_sha1_with_rsabowang($responseJson);
            }

            $responseStr = $signatrue . "||" . (base64_encode($responseJson));

            Log::info("销账向后台发送的报文加密前为：" . $responseJson);
        }
        Log::info("销账向后台发送的报文加密后为：".$responseStr);
//      将加签名之后的报文发送给浏览器
        $httpresp = new Response();
        $httpresp->contentType('text/plain','utf-8');
        $httpresp->data($responseStr);

        //$payamt=isset($requestBodyOfDecoded->message->info->input4) ? $requestBodyOfDecoded->message->info->input4 : 0;
        //身份证号
        $idno=isset($requestBodyOfDecoded->message->info->input2) ? $requestBodyOfDecoded->message->info->input2 : null;
        $totalAmt = isset($requestBodyOfDecoded->message->info->input4) ? $requestBodyOfDecoded->message->info->input4 : 0;
        $kind= isset($requestBodyOfDecoded->message->info->input5) ? $requestBodyOfDecoded->message->info->input5 : null;


        $totalAmt=number_format($totalAmt, 2);


        $wheresta = [];
        $wheresta['status'] = ['in', ['0','1','2']];

        $list=[];
        $lists= Db::table('fa_studentinfo')->where('idno',$idno)->where($wheresta)->select();
        if(count($lists)>1){
            foreach ($lists as $k => $v) {
                $paysum=$v['pay1']+$v['pay2']+$v['pay9']+$v['pay3']+$v['pay8'];
                $payone=number_format($paysum, 2);
                if($payone==$totalAmt){
                    $list=$v;
                }
            }
        }else{
            $list=$lists[0];
        }
       // $list= Db::table('fa_studentinfo')->where('idno',$idno)->where($wheresta)->order('id desc')->find();

        //工商学校只有学费，住宿费，教材费，学费pay1 ,住宿费pay2 ,教材费pay9 ,
        //教材费  pay3=pay9
        //学费住宿费 pay4=pay1+pay2+pay9 传过来永远是pay4
        //只可能由学费或者学费类 pay9=0时是学费类，



        if($kind=='A'){
            $kind='学费';
        }else if($kind=='B'){
            $kind='学杂费';
        }else if($kind=='C'){
            $kind='学费类';
        }else if($kind=='D'){
            $kind='学杂费类';
        }



        $channel=$respHead->channel;
        $userId  =  isset($requestBodyOfDecoded->message->info->userId) ?substr( $requestBodyOfDecoded->message->info->userId,0,16) : null;
        if($channel=='open'||$channel=='OPEN'){
            if(strpos($userId, 'alipay')=== 0){
                $channel='alipay';
            }else if(strpos($userId, 'odXG')=== 0){
                $channel='weixin';
            }
        }

        $nbill = new Bill();
        $nbill->data([
            'userId'  =>  $userId,
            'epayCode' => isset($requestBodyOfDecoded->message->info->epayCode) ? $requestBodyOfDecoded->message->info->epayCode : null,
            'traceNo' => isset($requestBodyOfDecoded->message->info->traceNo) ? $requestBodyOfDecoded->message->info->traceNo : null,
            'transCode' =>isset($requestBodyOfDecoded->message->info->transDate) ? $requestBodyOfDecoded->message->info->transDate : null,
            'studenntid'=>$list['id'],
            'branchCode'=>$list['xuezhi'],
            'grade'=>$list['grade'],
            'department'=>$list['department'],
            'classname'=>$list['classname'],
            'mete'=>$list['mete'],
            'school'=>$list['school'],
            'merchantId' =>isset($requestBodyOfDecoded->message->info->merchantId) ? $requestBodyOfDecoded->message->info->merchantId : null,
            'transDate' =>isset($requestBodyOfDecoded->message->info->transDate) ? $requestBodyOfDecoded->message->info->transDate : null,
            'timeStamp' =>  $respHead->timeStamp,
            'transSeqNum' => $respHead->transSeqNum,
            'channel' => $channel,
            'times' => date("Y-m-d H:i:s"),
            'state' =>  '1',
            'totalAmt' => isset($requestBodyOfDecoded->message->info->input4) ? $requestBodyOfDecoded->message->info->input4 : null,
            'input1' => isset($requestBodyOfDecoded->message->info->input1) ? $requestBodyOfDecoded->message->info->input1 : null,
            'input2' => isset($requestBodyOfDecoded->message->info->input2) ? $requestBodyOfDecoded->message->info->input2 : null,
            'input3' => isset($requestBodyOfDecoded->message->info->input3) ? $requestBodyOfDecoded->message->info->input3 : null,
            'input4' => isset($requestBodyOfDecoded->message->info->input4) ? $requestBodyOfDecoded->message->info->input4 : null,
            'input5' => $kind,
            ]);
        $nbill->save();


          if($kind=='学费'||$kind=='A'){
              $data = [
                  'status'=>'1',
              ];
              //需要去判断有没有交B
              $where['input5'] = ['=','学杂费'];

              $ttt= Db::table('fa_bill')->where('input2',$idno)->where($where)->find();
              if ($ttt==null){
                  $where22['input5'] = ['=','B'];
                  $ttt11= Db::table('fa_bill')->where('input2',$idno)->where($where22)->find();
                  if($ttt11==null){

                  }else{
                      //交齐
                      $data = [
                          'status'=>'3',
                      ];
                  }
                 //没有交
              }else{
                  //交齐
                  $data = [
                      'status'=>'3',
                  ];
              }
          }else if($kind=='学杂费'||$kind=='B'){
              $data = [
                  'status'=>'2',
              ];
              //需要去判断有没有交A
              $where1['input5'] = ['=','学费'];

              $tt2t= Db::table('fa_bill')->where('input2',$idno)->where($where1)->find();
              if ($tt2t==null){
                  //没有交
                  $where11['input5'] = ['=','A'];
                  $tt2t1= Db::table('fa_bill')->where('input2',$idno)->where($where11)->find();
                  if($tt2t1==null){

                  }else{
                      //交齐
                      $data = [
                          'status'=>'3',
                      ];
                  }
              }else{
                  //交齐
                  $data = [
                      'status'=>'3',
                  ];
              }
          }else if($kind=='学费类'||$kind=='C'){ //不需要交代收费只交学费住宿费
              $data = [
                  'status'=>'3',
              ];

          }else if($kind=='学杂费类'||$kind=='D'){ //不需要学费住宿费只交交代收费
              $data = [
                  'status'=>'3',
              ];
          }

        $studentinfo =new Studentinfo();



        $where = [];
//        $where['idno'] = ['=',isset($requestBodyOfDecoded->message->info->input2) ? $requestBodyOfDecoded->message->info->input2 : 0];
//        $where['status'] = ['in', ['0','1','2']];
        $where['id']=$list['id'];
        $studentinfo::update($data,$where);

        $httpresp->send();
    }
}
